from django.shortcuts import render, HttpResponse, redirect
import pymysql
import redis
import json
import jieba
from picture.functions import *

# Create your views here.
# 创建MySQL连接
mysql_conn = pymysql.connect(host='127.0.0.1', user='root', password='123456', db='msquare', charset='utf8')
cursor = mysql_conn.cursor(pymysql.cursors.DictCursor)

# 创建redis连接
redis_conn_6379 = redis.Redis(host='127.0.0.1', port=6379)
redis_conn_6389 = redis.Redis(host='127.0.0.1', port=6389)


# 搜索框
def search(request):
    '''

    :param request: types，当前搜索的范围（电影、图集）; content,搜索的内容；
    :return: 电影、图集概略信息
    '''
    # mysql_conn.ping(reconnect=True)
    types = int(request.GET.get('types', 0))
    content = request.GET.get('content', '')
    if types:
        return redirect('/picture/search/?content=' + content)
    else:
        return redirect('/movie/search/?content=' + content)


# 电影过滤器
def filter_movie(targets):
    # targets = eval(targets)
    id_pool = set()

    other_types = {33, 34, 37, 38, 39, 42, 46, 73, 77, 78}  # 其他类型待选的movie_id
    other_country = {i for i in range(50, 77)}              # 其他区域待选的movie_id

    if targets[0] or targets[1]:
        types_set = {-1} | {targets[0]} if targets[0] != -1 else other_types
        country_set = {-1} | {targets[1]} if targets[1] != -1 else other_country
        types_set = country_set if 0 in types_set else types_set
        country_set = types_set if 0 in country_set else country_set

        sql = "select t1.movie_id id " \
              "from (select movie_id from movie_t_movie_class where target_id in %s) t1, (select movie_id from movie_t_movie_class where target_id in %s) t2 " \
              "where t1.movie_id = t2.movie_id" % (repr(tuple(types_set)), repr(tuple(country_set)))
        try:
            cursor.execute(sql)
            id_pool |= {each['id'] for each in cursor.fetchall()}
        except:
            print(sql)

    if targets[2]:
        if id_pool:
            sql = "select movie_id id from movie_t_movie_class " \
                  "where movie_id in %s and target_id = %d" % (repr(tuple(id_pool)), targets[2])
        else:
            sql = "select movie_id id from movie_t_movie_class " \
                  "where target_id = %d" % targets[2]
        cursor.execute(sql)
        id_pool = {each['id'] for each in cursor.fetchall()}

    return id_pool


# 图片过滤器
def filter_picture(targets):
    id_pool = set()
    if targets:
        id_pool |= set(map(lambda x: int(x), redis_conn_6389.sinter(targets)))

    return id_pool


# 搜素结果
def search_result(request):
    content = request.GET.get('content', '')

    result = {'status': 200, 'info': [], 'nums': 0}

    # 处理搜索对象
    types = int(request.GET.get('types', 0))
    if types:
        table = 'picture_t_picture'
        add_num = 25
        redis_conn = redis_conn_6389
        targets = request.GET.get('targets', '[]')
        targets = json.loads(targets)
        id_pool = filter_picture(targets)
    else:
        table = 'movie_t_movie'
        add_num = 5
        redis_conn = redis_conn_6379
        targets = request.GET.get('targets', '{"type":0,"country":0,"release": 0}')
        targets = [each for each in json.loads(targets).values()]
        id_pool = filter_movie(targets)

    # 判断过滤
    if (targets and targets != [0, 0, 0]) and not id_pool:
        result['status'] = 404
        return HttpResponse(json.dumps(result))

    nums = request.GET.get('nums', '0')
    if content:
        words = list(jieba.cut(content))

        # 从redis中取出符合的movie_id
        all_id = set(map(lambda x: int(x), redis_conn.sinter(words)))
        if not all_id:
            result['status'] = 404
            return HttpResponse(json.dumps(result))
        else:
            if not id_pool:     # 按全部查询
                id_pool |= all_id
            else:               # 按过滤查询
                id_pool &= all_id
            # 首次请求返回查询结果数
            if nums == '0':
                cursor.execute(
                    "select count(*) counts from %s where id in %s" % (table, repr(tuple(id_pool | {-1, -2}))))
                result['nums'] = cursor.fetchone()['counts']

            sql = "select * from %s " \
                  "where id in %s limit %s, %s" % (table, repr(tuple(id_pool | {-1, -2})), nums, add_num)
    else:
        if not id_pool:     # 按全部
            filter_sql = "where id > -1"
        else:               # 按过滤查询
            filter_sql = "where id in %s" % repr(tuple(id_pool | {-1, -2}))
        # 首次请求返回查询结果数
        if nums == '0':
            cursor.execute("select count(*) counts from %s %s" % (table, filter_sql))
            result['nums'] = cursor.fetchone()['counts']

        sql = "select * from %s %s limit %s, %s" % (table, filter_sql, nums, add_num)
    try:
        cursor.execute(sql)
        result['info'] = cursor.fetchall()
        if (not (result['nums'] or nums)) or (not len(result['info'])):
            result['status'] = 404
    except:
        print(sql)
        result['status'] = 500

    return HttpResponse(json.dumps(result))


# 搜索框推荐
def search_recommend(request):
    '''

    :param request: types，0为电影，1为图片;
    :return: 电影id，电影名字；图集标签id，图集标签名字；
    '''
    # mysql_conn.ping(reconnect=True)
    result = {'status': 200}
    types = int(request.GET.get('types', 0))

    sql = "select media_id id from m2_t_search where type=%d" % types
    search_info = []
    try:
        cursor.execute(sql)
        search_info = cursor.fetchall()
    except:
        print(sql)
        result['status'] = 500
    id_pool = tuple([each['id'] for each in search_info] + [-1, -2])
    if types:  # 图集
        sql = "select id, target from picture_t_picture_target where id in %s" % repr(id_pool)
    else:
        sql = "select id, movie_name from movie_t_movie where id in %s" % repr(id_pool)

    try:
        cursor.execute(sql)
        result['info'] = cursor.fetchall()
    except:
        print(sql)
        result['status'] = 500

    return HttpResponse(json.dumps(result))


def index(request):
    user_id = request.session.get('user_id', -1)
    return render(request, 'index.html', {'user_id': user_id})

